import React, { useState, useRef } from 'react'
import {
  Select,
  Input,
  Button,
  Tabs,
  Table,
  Tag,
  Typography,
  message,
  Upload,
} from 'antd'
import {
  SendOutlined,
  PlusOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  ClearOutlined,
} from '@ant-design/icons'
import Editor from '@monaco-editor/react'
import { CancelRequest, SendRequest } from '../../../wailsjs/go/main/HTTPApp'
import './index.scss'
import { httpClient } from '../../../wailsjs/go/models'
import { AdaptSize } from '../../utils/http'

const { TabPane } = Tabs
const { Text } = Typography

// 定义请求参数的类型
interface Param {
  id: number
  key: string
  value: string
}

// 定义响应测试结果类型
interface TestResult {
  name: string
  passed: boolean
}

interface FormDataParam {
  id: number
  key: string
  type: 'text' | 'file' | 'array'
  value: string | File
}

const HttpPage: React.FC = () => {
  const [method, setMethod] = useState<string>('GET')

  const [url, setUrl] = useState<string>('')
  const [params, setParams] = useState<Param[]>([{ id: 1, key: '', value: '' }])
  const [headers, setHeaders] = useState<Param[]>([
    { id: 1, key: '', value: '' },
  ])
  const [body, setBody] = useState<string>('')
  const [authType, setAuthType] = useState<string>('none')
  const [authUsername, setAuthUsername] = useState<string>('')
  const [authPassword, setAuthPassword] = useState<string>('')
  const [authToken, setAuthToken] = useState<string>('')
  const [responseStatus, setResponseStatus] = useState<string | null>(null)
  const [responseSize, setResponseSize] = useState<string | null>(null)
  const [responseTime, setResponseTime] = useState<string | null>(null)
  const [responseBody, setResponseBody] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [responseContentType, setResponseContentType] = useState<string | null>(
    null,
  )
  const [responseLanguage, setResponseLanguage] = useState<string>('json')
  const [responseRenderMode, setResponseRenderMode] = useState<
    'raw' | 'preview'
  >('raw')
  const [responseHeaders, setResponseHeaders] = useState<{
    [key: string]: string
  } | null>(null)
  const [testResults, setTestResults] = useState<TestResult[]>([
    { name: 'Response Code equal to 200', passed: false },
    { name: 'Response Time < 500', passed: false },
    { name: 'Header Content-Type contains application/json', passed: false },
  ])
  const [bodyType, setBodyType] = useState<'raw' | 'form-data'>('raw')
  const [formDataParams, setFormDataParams] = useState<FormDataParam[]>([
    { id: 1, key: '', type: 'text', value: '' },
  ])

  const requestEditorRef = useRef(null)
  const responseEditorRef = useRef(null)

  // 添加参数行
  const addParamRow = () => {
    setParams([...params, { id: Date.now(), key: '', value: '' }])
  }

  // 添加请求头行
  const addHeaderRow = () => {
    setHeaders([...headers, { id: Date.now(), key: '', value: '' }])
  }

  // 更新参数
  const handleParamChange = (
    id: number,
    field: 'key' | 'value',
    value: string,
  ) => {
    // 更新参数
    const updatedParams = params.map((param) =>
      param.id === id ? { ...param, [field]: value } : param,
    )

    // 更新状态
    setParams(updatedParams)
  }

  // 更新请求头
  const handleHeaderChange = (
    id: number,
    field: 'key' | 'value',
    value: string,
  ) => {
    // 更新请求头
    const updatedHeaders = headers.map((header) =>
      header.id === id ? { ...header, [field]: value } : header,
    )

    // 更新状态
    setHeaders(updatedHeaders)
  }

  // 删除参数行
  const removeParamRow = (id: number) => {
    setParams(params.filter((param) => param.id !== id))
  }

  // 删除请求头行
  const removeHeaderRow = (id: number) => {
    setHeaders(headers.filter((header) => header.id !== id))
  }

  // 清空所有参数
  const clearAllParams = () => {
    setParams([{ id: Date.now(), key: '', value: '' }]) // 重置为一个空行
    message.success('已清空所有参数')
  }

  // 清空所有请求头
  const clearAllHeaders = () => {
    setHeaders([{ id: Date.now(), key: '', value: '' }]) // 重置为一个空行
    message.success('已清空所有请求头')
  }

  // 添加常用请求头
  const addCommonHeader = (headerKey: string, headerValue: string) => {
    // 检查是否已存在该请求头
    const existingHeader = headers.find((h) => h.key === headerKey)

    if (existingHeader) {
      // 如果已存在，更新值
      const updatedHeaders = headers.map((h) =>
        h.key === headerKey ? { ...h, value: headerValue } : h,
      )
      setHeaders(updatedHeaders)
    } else {
      // 如果不存在，添加新的
      setHeaders([
        ...headers,
        { id: Date.now(), key: headerKey, value: headerValue },
      ])
    }

    message.success(`已添加 ${headerKey} 请求头`)
  }

  // 同步参数到URL
  const syncParamsToUrl = () => {
    // 确保基础URL不包含查询参数
    const baseUrl = url.split('?')[0]

    // 构建查询字符串
    const queryString = buildQueryString(params)

    if (queryString) {
      // 构建完整URL（使用干净的基础URL）
      const fullUrl = `${baseUrl}?${queryString}`
      message.success('已将参数同步到URL')
      return fullUrl
    }

    // 如果没有有效参数，只返回基础URL
    return baseUrl
  }

  // 解析URL并提取查询参数
  const parseUrlAndExtractParams = (inputUrl: string) => {
    try {
      // 检查URL是否包含查询参数
      if (!inputUrl.includes('?')) {
        return { baseUrl: inputUrl, queryParams: [] }
      }

      // 拆分URL和查询字符串
      const [baseUrl, queryString] = inputUrl.split('?')

      // 如果没有查询字符串，直接返回
      if (!queryString) {
        return { baseUrl, queryParams: [] }
      }

      // 解析查询参数
      const queryParams: Param[] = queryString
        .split('&')
        .filter((param) => param.trim() !== '')
        .map((param) => {
          const [key, value] = param.split('=').map(decodeURIComponent)
          return {
            id: Date.now() + Math.random(), // 生成唯一ID
            key: key || '',
            value: value || '',
          }
        })

      return { baseUrl, queryParams }
    } catch (error) {
      console.error('Error parsing URL:', error)
      return { baseUrl: inputUrl, queryParams: [] }
    }
  }

  // 将参数转换为查询字符串
  const buildQueryString = (paramsList: Param[]): string => {
    // 过滤掉空参数
    const validParams = paramsList.filter((p) => p.key.trim() !== '')

    if (validParams.length === 0) {
      return ''
    }

    // 构建查询字符串
    return validParams
      .map(
        (p) =>
          `${encodeURIComponent(p.key)}=${encodeURIComponent(p.value || '')}`,
      )
      .join('&')
  }

  // 处理URL输入变化
  const handleUrlChange = (inputUrl: string) => {
    // 检查URL是否发生了实质性变化（不仅仅是查询参数的变化）
    const currentBaseUrl = url.split('?')[0]
    const newBaseUrlPart = inputUrl.split('?')[0]
    const isBaseUrlChanged = currentBaseUrl !== newBaseUrlPart

    // 如果URL包含查询参数，则拆分并更新
    if (inputUrl.includes('?')) {
      const { baseUrl, queryParams } = parseUrlAndExtractParams(inputUrl)

      // 更新URL为基础URL（不含查询参数）
      setUrl(baseUrl)

      // 如果有查询参数，则更新参数表格
      if (queryParams.length > 0) {
        // 如果基础URL发生了变化，则完全替换参数
        // 否则，仅添加新参数（避免重复添加）
        if (isBaseUrlChanged) {
          // 完全替换参数
          setParams(queryParams)
          message.success(`已从新URL中提取${queryParams.length}个查询参数`)
        } else {
          // 检查是否是重复粘贴相同的URL
          // 获取现有参数的键
          const existingKeys = new Set(params.map((p) => p.key))

          // 过滤出不在现有参数中的新参数
          const newParams = queryParams.filter((p) => !existingKeys.has(p.key))

          if (newParams.length > 0) {
            // 只添加新的参数
            setParams([...params, ...newParams])
            message.success(`已从URL中提取${newParams.length}个新查询参数`)
          } else {
            // 如果没有新参数，不做任何更改
            message.info('未发现新的查询参数')
          }
        }
      }
    } else {
      // 如果URL不包含查询参数
      setUrl(inputUrl)

      // 如果基础URL发生了变化，清空参数表
      if (isBaseUrlChanged) {
        setParams([{ id: Date.now(), key: '', value: '' }]) // 重置为一个空行
      }
    }
  }

  // 处理请求编辑器挂载
  const handleRequestEditorDidMount = (editor: any, _monaco: any) => {
    requestEditorRef.current = editor
    configureEditor(editor)
  }

  // 处理响应编辑器挂载
  const handleResponseEditorDidMount = (editor: any, _monaco: any) => {
    responseEditorRef.current = editor
    configureEditor(editor)
  }

  // 配置编辑器以更好地处理长文本，强制使用换行显示，无横向滚动
  const configureEditor = (editor: any) => {
    editor.updateOptions({
      wordWrap: 'on',
      wrappingIndent: 'same',
      wrappingStrategy: 'advanced',
      scrollBeyondLastLine: true,
      lineNumbers: 'on',
      lineNumbersMinChars: 3,
    })
  }

  // 添加自定义CSS以确保长文本正确显示
  React.useEffect(() => {
    const styleSheet = document.createElement('style')
    styleSheet.textContent = `
      /* 基本编辑器样式 */
      .monaco-editor .view-line {
        word-wrap: break-word !important;
        white-space: pre-wrap !important;
      }
    `
    document.head.appendChild(styleSheet)

    return () => {
      document.head.removeChild(styleSheet)
    }
  }, [])

  // 添加 form-data 参数行
  const addFormDataParamRow = () => {
    setFormDataParams((params) => [
      ...params,
      { id: Date.now(), key: '', type: 'text', value: '' },
    ])
  }

  // 删除 form-data 参数行
  const removeFormDataParamRow = (id: number) => {
    setFormDataParams((params) => params.filter((param) => param.id !== id))
  }

  // 更新 form-data 参数
  const handleFormDataParamChange = (
    id: number,
    field: 'key' | 'type' | 'value',
    value: any,
  ) => {
    setFormDataParams((params) =>
      params.map((param) =>
        param.id === id ? { ...param, [field]: value } : param,
      ),
    )
  }

  // 清空所有 form-data 参数
  const clearAllFormDataParams = () => {
    setFormDataParams([{ id: Date.now(), key: '', type: 'text', value: '' }])
    message.success('已清空所有 form-data 参数')
  }

  // 1. 辅助函数：File 转 base64
  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = () => {
        const base64 = (reader.result as string).split(',')[1]
        resolve(base64)
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }

  // 2. 辅助函数：构造 files 和 params
  const buildFilesAndParams = async (formDataParams: FormDataParam[]) => {
    const files: { [key: string]: string } = {}
    const paramsArr: Param[] = []
    for (const param of formDataParams) {
      if (!param.key) continue
      if (param.type === 'file' && param.value instanceof File) {
        const b64 = await fileToBase64(param.value)
        files[param.key] = b64
      } else if (param.type === 'array') {
        ;(param.value as string).split(',').forEach((v) => {
          paramsArr.push({ id: Date.now(), key: param.key, value: v.trim() })
        })
      } else {
        paramsArr.push({
          id: Date.now(),
          key: param.key,
          value: param.value as string,
        })
      }
    }
    return { files, paramsArr }
  }

  // 发送请求的处理函数
  const handleSendRequest = async () => {
    if (!url) {
      message.error('请输入请求URL')
      return
    }

    setIsLoading(true)
    setResponseStatus(null)
    setResponseSize(null)
    setResponseTime(null)
    setResponseBody(null)
    setResponseContentType(null)
    setResponseHeaders(null)
    setResponseLanguage('json')
    setResponseRenderMode('raw')

    // 确保基础URL不包含查询参数
    const baseUrl = url.split('?')[0]

    // 构建完整URL（基础URL + 查询参数）
    const queryString = buildQueryString(params)
    const fullUrl = queryString ? `${baseUrl}?${queryString}` : baseUrl

    // 构建请求头对象
    const headersObj: { [key: string]: string } = {}

    // 添加表单中的请求头
    headers.forEach((header) => {
      if (header.key.trim() !== '') {
        headersObj[header.key] = header.value
      }
    })

    // 添加认证信息
    if (authType === 'basic') {
      // Basic Auth
      const base64Credentials = btoa(`${authUsername}:${authPassword}`)
      headersObj['Authorization'] = `Basic ${base64Credentials}`
    } else if (authType === 'bearer') {
      // Bearer Token
      headersObj['Authorization'] = `Bearer ${authToken}`
    }

    console.log('Sending request:', {
      method,
      url: fullUrl.trim(),
      headers: headersObj,
      params,
      body,
    })

    if (bodyType === 'form-data') {
      setIsLoading(true)
      setResponseStatus(null)
      setResponseSize(null)
      setResponseTime(null)
      setResponseBody(null)
      setResponseContentType(null)
      setResponseHeaders(null)
      setResponseLanguage('json')
      setResponseRenderMode('raw')

      try {
        const { files, paramsArr } = await buildFilesAndParams(formDataParams)
        const request = httpClient.HTTPRequest.createFrom({
          method,
          url: fullUrl.trim(),
          headers: headersObj,
          params: paramsArr,
          body: '',
          files,
        })
        const response = await SendRequest(request)
        if (response.error) {
          throw new Error(response.error)
        }
        const duration = response.time
        setResponseStatus(`${response.status}`)
        setResponseSize(AdaptSize(response.size))
        setResponseTime(`${duration} ms`)
        setResponseBody(response.body)
        setResponseContentType(response.contentType)
        setResponseHeaders(response.headers)
        // 内容类型判断和渲染模式
        if (response.contentType) {
          if (response.contentType.includes('application/json')) {
            setResponseLanguage('json')
            setResponseRenderMode('raw')
          } else if (response.contentType.includes('text/html')) {
            setResponseLanguage('html')
            setResponseRenderMode('preview')
          } else if (
            response.contentType.includes('text/xml') ||
            response.contentType.includes('application/xml')
          ) {
            setResponseLanguage('xml')
            setResponseRenderMode('raw')
          } else if (response.contentType.includes('text/css')) {
            setResponseLanguage('css')
            setResponseRenderMode('raw')
          } else if (
            response.contentType.includes('text/javascript') ||
            response.contentType.includes('application/javascript')
          ) {
            setResponseLanguage('javascript')
            setResponseRenderMode('raw')
          } else {
            setResponseLanguage('plaintext')
            setResponseRenderMode('raw')
          }
        } else {
          // 尝试通过内容分析来判断类型
          const bodyContent = response.body.trim()
          if (bodyContent.startsWith('{') && bodyContent.endsWith('}')) {
            try {
              JSON.parse(bodyContent)
              setResponseLanguage('json')
              setResponseRenderMode('raw')
            } catch {
              setResponseLanguage('plaintext')
              setResponseRenderMode('raw')
            }
          } else if (
            bodyContent.startsWith('<') &&
            bodyContent.includes('</html>')
          ) {
            setResponseLanguage('html')
            setResponseRenderMode('preview')
          } else {
            setResponseLanguage('plaintext')
            setResponseRenderMode('raw')
          }
        }
        // 测试结果
        const newTestResults = [
          {
            name: 'Response Code equal to 200',
            passed: response.status === 200,
          },
          { name: 'Response Time < 500', passed: duration < 500 },
          {
            name: 'Header Content-Type contains application/json',
            passed: response.contentType?.includes('application/json') || false,
          },
        ]
        setTestResults(newTestResults)
      } catch (error) {
        console.error('API request failed:', error)
        if (error instanceof Error) {
          message.error('请求失败: ' + error.message)
        } else {
          if (typeof error === 'string' && error.includes('context canceled')) {
            message.warning('请求已取消')
          } else {
            message.error('请求失败: 未知错误')
          }
        }
        setResponseStatus('Error')
        setResponseBody(
          error instanceof Error ? error.message : 'An unknown error occurred.',
        )
        setResponseLanguage('plaintext')
        setResponseHeaders({
          Error:
            error instanceof Error
              ? error.message
              : 'An unknown error occurred.',
          Status: 'Error',
        })
        setTestResults(testResults.map((test) => ({ ...test, passed: false })))
      } finally {
        setIsLoading(false)
      }
      return
    } else {
      try {
        // 构建请求对象
        const request = httpClient.HTTPRequest.createFrom({
          method,
          url: fullUrl, // 使用包含查询参数的完整URL
          headers: headersObj, // 添加自定义请求头
          params: [], // 参数已经包含在URL中，这里传空数组
          body: body,
        })

        // 调用Go后端函数发送请求
        const response = await SendRequest(request)

        if (response.error) {
          throw new Error(response.error)
        }

        // 设置响应状态
        setResponseStatus(`${response.status}`)
        setResponseSize(AdaptSize(response.size))
        setResponseTime(`${response.time} ms`)
        setResponseBody(response.body)
        setResponseContentType(response.contentType)

        // 调试响应头信息
        console.log('Response headers:', response.headers)

        // 确保headers是一个对象而不是undefined或null
        if (response.headers && Object.keys(response.headers).length > 0) {
          setResponseHeaders(response.headers)
        } else {
          // 如果没有headers，创建一个包含Content-Type的对象
          const defaultHeaders: { [key: string]: string } = {}
          if (response.contentType) {
            defaultHeaders['Content-Type'] = response.contentType
          }
          setResponseHeaders(defaultHeaders)
        }

        // 根据内容类型设置响应编辑器的语言和渲染模式
        if (response.contentType) {
          if (response.contentType.includes('application/json')) {
            setResponseLanguage('json')
            // JSON默认使用raw模式，因为Monaco编辑器已经提供了良好的格式化
            setResponseRenderMode('raw')
          } else if (response.contentType.includes('text/html')) {
            setResponseLanguage('html')
            // HTML可以提供预览功能
            setResponseRenderMode('preview')
          } else if (
            response.contentType.includes('text/xml') ||
            response.contentType.includes('application/xml')
          ) {
            setResponseLanguage('xml')
            setResponseRenderMode('raw')
          } else if (response.contentType.includes('text/css')) {
            setResponseLanguage('css')
            setResponseRenderMode('raw')
          } else if (
            response.contentType.includes('text/javascript') ||
            response.contentType.includes('application/javascript')
          ) {
            setResponseLanguage('javascript')
            setResponseRenderMode('raw')
          } else {
            setResponseLanguage('plaintext')
            setResponseRenderMode('raw')
          }
        } else {
          // 尝试通过内容分析来判断类型
          const bodyContent = response.body.trim()
          if (bodyContent.startsWith('{') && bodyContent.endsWith('}')) {
            // 可能是JSON
            try {
              JSON.parse(bodyContent)
              setResponseLanguage('json')
              setResponseRenderMode('raw')
            } catch {
              setResponseLanguage('plaintext')
              setResponseRenderMode('raw')
            }
          } else if (
            bodyContent.startsWith('<') &&
            bodyContent.includes('</html>')
          ) {
            // 可能是HTML
            setResponseLanguage('html')
            setResponseRenderMode('preview')
          } else {
            setResponseLanguage('plaintext') // 默认为纯文本
            setResponseRenderMode('raw')
          }
        }

        // 更新测试结果
        const newTestResults = [
          {
            name: 'Response Code equal to 200',
            passed: response.status === 200,
          },
          { name: 'Response Time < 500', passed: response.time < 500 },
          {
            name: 'Header Content-Type contains application/json',
            passed: response.contentType?.includes('application/json') || false,
          },
        ]

        // 调试测试结果
        console.log('Test results:', newTestResults)

        setTestResults(newTestResults)
      } catch (error) {
        console.error('API request failed:', error)
        if (error instanceof Error) {
          message.error('请求失败: ' + error.message)
        } else {
          if (typeof error === 'string' && error.includes('context canceled')) {
            message.warning('请求已取消')
          } else {
            message.error('请求失败: 未知错误')
          }
        }
        setResponseStatus('Error')
        setResponseBody(
          error instanceof Error ? error.message : 'An unknown error occurred.',
        )
        setResponseLanguage('plaintext')
        setResponseHeaders({
          Error:
            error instanceof Error
              ? error.message
              : 'An unknown error occurred.',
          Status: 'Error',
        })
        setTestResults(testResults.map((test) => ({ ...test, passed: false })))
      } finally {
        setIsLoading(false)
      }
    }
  }

  // 参数表格列定义
  const paramColumns = [
    {
      title: 'Key',
      dataIndex: 'key',
      key: 'key',
      render: (_: any, record: Param) => (
        <Input
          placeholder="参数名"
          value={record.key}
          onChange={(e) => handleParamChange(record.id, 'key', e.target.value)}
        />
      ),
    },
    {
      title: 'Value',
      dataIndex: 'value',
      key: 'value',
      render: (_: any, record: Param) => (
        <Input
          placeholder="参数值"
          value={record.value}
          onChange={(e) =>
            handleParamChange(record.id, 'value', e.target.value)
          }
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: Param) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => removeParamRow(record.id)}
        />
      ),
    },
  ]

  const handleAbort = async () => {
    // 取消已经发送的请求
    setIsLoading(false)
    await CancelRequest()
  }

  return (
    <div className="http-client-container">
      {/* 请求头部: 方法选择和 URL 输入 */}
      <div className="request-header">
        <Select
          value={method}
          onChange={(value) => setMethod(value)}
          style={{ width: 100 }}
          optionLabelProp="label"
          dropdownStyle={{ minWidth: '100px' }}
          className="method-select"
          popupMatchSelectWidth={false}
          listHeight={280}
        >
          <Select.Option
            value="GET"
            label={<span className="http-method get">GET</span>}
          >
            <span className="http-method get">GET</span>
          </Select.Option>
          <Select.Option
            value="POST"
            label={<span className="http-method post">POST</span>}
          >
            <span className="http-method post">POST</span>
          </Select.Option>
          <Select.Option
            value="PUT"
            label={<span className="http-method put">PUT</span>}
          >
            <span className="http-method put">PUT</span>
          </Select.Option>
          <Select.Option
            value="DELETE"
            label={<span className="http-method delete">DELETE</span>}
          >
            <span className="http-method delete">DELETE</span>
          </Select.Option>
          <Select.Option
            value="PATCH"
            label={<span className="http-method patch">PATCH</span>}
          >
            <span className="http-method patch">PATCH</span>
          </Select.Option>
          <Select.Option
            value="OPTIONS"
            label={<span className="http-method options">OPTIONS</span>}
          >
            <span className="http-method options">OPTIONS</span>
          </Select.Option>
          <Select.Option
            value="HEAD"
            label={<span className="http-method head">HEAD</span>}
          >
            <span className="http-method head">HEAD</span>
          </Select.Option>
          <Select.Option
            value="TRACE"
            label={<span className="http-method trace">TRACE</span>}
          >
            <span className="http-method trace">TRACE</span>
          </Select.Option>
        </Select>
        <Input
          value={url}
          onChange={(e) => handleUrlChange(e.target.value)}
          placeholder="输入请求 URL"
          style={{ flex: 1 }}
          addonAfter={
            <Button
              type="text"
              size="small"
              icon={<SyncOutlined />}
              onClick={() => setUrl(syncParamsToUrl())}
              title="将参数同步到URL"
              style={{ border: 'none', padding: '0 8px' }}
            />
          }
        />
        <Button
          type="primary"
          icon={<SendOutlined />}
          onClick={handleSendRequest}
          loading={isLoading}
          danger={isLoading ? true : false}
        >
          {isLoading ? '发送中' : '发送'}
        </Button>
        {isLoading && (
          <Button danger icon={<CloseCircleOutlined />} onClick={handleAbort}>
            取消
          </Button>
        )}
      </div>

      {/* 请求和响应面板 */}
      <div className="request-response-container">
        {/* 请求面板 */}
        <div className="request-panel">
          <div className="panel-header">
            <Text strong style={{ color: 'rgba(0, 0, 0, 0.85)' }}>
              Request
            </Text>
          </div>
          <div className="panel-content">
            <Tabs defaultActiveKey="params" style={{ height: '100%' }}>
              <TabPane tab="Params" key="params" style={{ overflowY: 'auto' }}>
                <div
                  style={{
                    margin: '4px 0',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}
                >
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    提示: 您可以直接在URL中输入带参数的地址 (例如:
                    https://example.com/api?key=value&key2=value2)，系统会自动提取参数
                  </Text>
                  <Button
                    type="text"
                    icon={<ClearOutlined />}
                    onClick={clearAllParams}
                    size="small"
                    title="清空所有参数"
                  >
                    清空参数
                  </Button>
                </div>
                <Table
                  columns={paramColumns}
                  dataSource={params}
                  pagination={false}
                  rowKey="id"
                  size="small"
                  style={{ height: 'calc(100% - 40px)' }}
                  footer={() => (
                    <Button
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={addParamRow}
                      block
                    >
                      添加参数
                    </Button>
                  )}
                />
              </TabPane>
              <TabPane
                key="body"
                tab={
                  <span
                    style={{ display: 'flex', alignItems: 'center', gap: 2 }}
                  >
                    Body
                    <Select
                      value={bodyType}
                      onChange={setBodyType}
                      options={[
                        { value: 'raw', label: 'Raw (JSON)' },
                        { value: 'form-data', label: 'Form Data' },
                      ]}
                      style={{ width: 110, height: 28, marginLeft: 4 }}
                      size="small"
                    />
                  </span>
                }
              >
                {bodyType === 'raw' ? (
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'column',
                      height: '100%',
                    }}
                  >
                    <div className="monaco-editor-container">
                      <Editor
                        height={
                          method === 'GET' || method === 'HEAD' ? '90%' : '100%'
                        }
                        defaultLanguage="json"
                        value={body}
                        onChange={(value) => setBody(value || '')}
                        theme="light"
                        options={{
                          minimap: { enabled: true, autohide: true },
                          scrollBeyondLastLine: true,
                          fontSize: 13,
                          readOnly: method === 'GET' || method === 'HEAD',
                          readOnlyMessage: {
                            value: 'GET/HEAD 请求通常不包含 Body',
                            supportThemeIcons: true,
                            isTrusted: true,
                            supportHtml: true,
                          },
                          wordWrap: 'on',
                          wrappingIndent: 'same',
                          wrappingStrategy: 'advanced',
                          lineNumbers: 'on',
                          lineNumbersMinChars: 3,
                        }}
                        onMount={handleRequestEditorDidMount}
                      />
                    </div>
                    {(method === 'GET' || method === 'HEAD') && (
                      <Text
                        type="secondary"
                        style={{ paddingTop: 8, display: 'block' }}
                      >
                        GET/HEAD 请求通常不包含 Body
                      </Text>
                    )}
                  </div>
                ) : (
                  <div
                    className="form-data-container"
                    style={{ height: '100%' }}
                  >
                    <div
                      style={{
                        margin: '4px 0',
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                      }}
                    >
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        支持文件上传和数组参数，数组用逗号分隔
                      </Text>
                      <Button
                        type="text"
                        icon={<ClearOutlined />}
                        onClick={clearAllFormDataParams}
                        size="small"
                        title="清空所有参数"
                      >
                        清空参数
                      </Button>
                    </div>
                    <Table
                      style={{ overflowY: 'auto', height: 'calc(100% - 40px)' }}
                      columns={[
                        {
                          title: 'Key',
                          dataIndex: 'key',
                          render: (_: any, record: FormDataParam) => (
                            <Input
                              value={record.key}
                              onChange={(e) =>
                                handleFormDataParamChange(
                                  record.id,
                                  'key',
                                  e.target.value,
                                )
                              }
                              placeholder="参数名"
                            />
                          ),
                        },
                        {
                          title: 'Type',
                          dataIndex: 'type',
                          render: (_: any, record: FormDataParam) => (
                            <Select
                              value={record.type}
                              onChange={(value) =>
                                handleFormDataParamChange(
                                  record.id,
                                  'type',
                                  value,
                                )
                              }
                              options={[
                                { value: 'text', label: 'Text' },
                                { value: 'file', label: 'File' },
                                { value: 'array', label: 'Array' },
                              ]}
                              style={{ width: 80 }}
                            />
                          ),
                        },
                        {
                          title: 'Value',
                          dataIndex: 'value',
                          render: (_: any, record: FormDataParam) =>
                            record.type === 'file' ? (
                              <Upload
                                showUploadList={false}
                                beforeUpload={(file) => {
                                  handleFormDataParamChange(
                                    record.id,
                                    'value',
                                    file,
                                  )
                                  return false // Prevent auto upload
                                }}
                                accept="*"
                              >
                                <Button size="small">选择文件</Button>
                                {record.value &&
                                  typeof record.value === 'object' && (
                                    <span style={{ marginLeft: 8 }}>
                                      {(record.value as File).name}
                                    </span>
                                  )}
                              </Upload>
                            ) : (
                              <Input
                                value={record.value as string}
                                onChange={(e) =>
                                  handleFormDataParamChange(
                                    record.id,
                                    'value',
                                    e.target.value,
                                  )
                                }
                                placeholder={
                                  record.type === 'array'
                                    ? '用逗号分隔'
                                    : '参数值'
                                }
                              />
                            ),
                        },
                        {
                          title: '操作',
                          key: 'action',
                          render: (_: any, record: FormDataParam) => (
                            <Button
                              type="text"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => removeFormDataParamRow(record.id)}
                            />
                          ),
                        },
                      ]}
                      dataSource={formDataParams}
                      pagination={false}
                      rowKey="id"
                      size="small"
                      footer={() => (
                        <Button
                          type="dashed"
                          icon={<PlusOutlined />}
                          onClick={addFormDataParamRow}
                          block
                        >
                          添加参数
                        </Button>
                      )}
                    />
                  </div>
                )}
              </TabPane>
              <TabPane
                tab="Headers"
                key="headers"
                style={{ overflowY: 'auto' }}
              >
                <div
                  style={{
                    margin: '4px 0',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}
                >
                  <div>
                    <Button
                      type="link"
                      size="small"
                      onClick={() =>
                        addCommonHeader('Content-Type', 'application/json')
                      }
                    >
                      添加 JSON
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      onClick={() =>
                        addCommonHeader(
                          'Content-Type',
                          'application/x-www-form-urlencoded',
                        )
                      }
                    >
                      添加 Form
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      onClick={() => addCommonHeader('Accept', '*/*')}
                    >
                      添加 Accept
                    </Button>
                  </div>
                  <Button
                    type="text"
                    icon={<ClearOutlined />}
                    onClick={clearAllHeaders}
                    size="small"
                    title="清空所有请求头"
                  >
                    清空请求头
                  </Button>
                </div>
                <Table
                  columns={[
                    {
                      title: 'Key',
                      dataIndex: 'key',
                      key: 'key',
                      render: (_: any, record: Param) => (
                        <Input
                          placeholder="请求头名称"
                          value={record.key}
                          onChange={(e) =>
                            handleHeaderChange(record.id, 'key', e.target.value)
                          }
                        />
                      ),
                    },
                    {
                      title: 'Value',
                      dataIndex: 'value',
                      key: 'value',
                      render: (_: any, record: Param) => (
                        <Input
                          placeholder="请求头值"
                          value={record.value}
                          onChange={(e) =>
                            handleHeaderChange(
                              record.id,
                              'value',
                              e.target.value,
                            )
                          }
                        />
                      ),
                    },
                    {
                      title: '操作',
                      key: 'action',
                      width: 100,
                      render: (_: any, record: Param) => (
                        <Button
                          type="text"
                          danger
                          icon={<DeleteOutlined />}
                          onClick={() => removeHeaderRow(record.id)}
                        />
                      ),
                    },
                  ]}
                  dataSource={headers}
                  pagination={false}
                  rowKey="id"
                  size="small"
                  footer={() => (
                    <Button
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={addHeaderRow}
                      block
                    >
                      添加请求头
                    </Button>
                  )}
                />
              </TabPane>
              <TabPane tab="Auth" key="auth">
                <div className="auth-container" style={{ marginTop: 8 }}>
                  <div className="auth-type-selector">
                    <div className="auth-label">
                      <Text strong>认证类型</Text>
                    </div>
                    <Select
                      value={authType}
                      onChange={(value) => setAuthType(value)}
                      style={{ width: '100%' }}
                      size="middle"
                      popupMatchSelectWidth={false}
                    >
                      <Select.Option value="none">无认证</Select.Option>
                      <Select.Option value="basic">Basic Auth</Select.Option>
                      <Select.Option value="bearer">Bearer Token</Select.Option>
                    </Select>
                  </div>

                  {authType === 'basic' && (
                    <div className="auth-form">
                      <div className="auth-form-item">
                        <div className="auth-label">
                          <Text>用户名</Text>
                        </div>
                        <Input
                          placeholder="输入用户名"
                          value={authUsername}
                          onChange={(e) => setAuthUsername(e.target.value)}
                          prefix={<span className="auth-input-icon">👤</span>}
                        />
                      </div>
                      <div className="auth-form-item">
                        <div className="auth-label">
                          <Text>密码</Text>
                        </div>
                        <Input.Password
                          placeholder="输入密码"
                          value={authPassword}
                          onChange={(e) => setAuthPassword(e.target.value)}
                          prefix={<span className="auth-input-icon">🔑</span>}
                        />
                      </div>
                    </div>
                  )}

                  {authType === 'bearer' && (
                    <div className="auth-form">
                      <div className="auth-form-item">
                        <div className="auth-label">
                          <Text>Token</Text>
                        </div>
                        <Input
                          placeholder="输入 Bearer Token"
                          value={authToken}
                          onChange={(e) => setAuthToken(e.target.value)}
                          prefix={<span className="auth-input-icon">🔒</span>}
                        />
                      </div>
                    </div>
                  )}

                  {authType !== 'none' && (
                    <div className="auth-info">
                      <div className="auth-info-icon">ℹ️</div>
                      <div className="auth-info-text">
                        <Text type="secondary">
                          认证信息将自动添加到请求头中，无需手动添加
                          Authorization 请求头
                        </Text>
                      </div>
                    </div>
                  )}
                </div>
              </TabPane>
            </Tabs>
          </div>
        </div>

        {/* 响应面板 */}
        <div className="response-panel">
          <div className="panel-header">
            <Text strong style={{ color: 'rgba(0, 0, 0, 0.85)' }}>
              Response
            </Text>
            <div className="response-status-info">
              {responseStatus && (
                <div className="status-item">
                  <span className="info-label">状态:</span>
                  <span
                    className={`info-value ${responseStatus.includes('200') ? 'success' : 'error'}`}
                  >
                    {responseStatus.includes('200') ? '200 OK' : responseStatus}
                  </span>
                </div>
              )}
              {responseTime && (
                <div className="time-item">
                  <span className="info-label">时间:</span>
                  <span className="info-value">{responseTime}</span>
                </div>
              )}
              {responseSize && (
                <div className="size-item">
                  <span className="info-label">大小:</span>
                  <span className="info-value">{responseSize}</span>
                </div>
              )}
              {!responseStatus && !isLoading && (
                <div className="waiting-item">
                  <span className="info-value">等待请求</span>
                </div>
              )}
              {isLoading && (
                <div className="loading-item">
                  <ClockCircleOutlined style={{ marginRight: '4px' }} />
                  <span className="info-value">请求中...</span>
                </div>
              )}
            </div>
          </div>
          <div className="panel-content">
            <Tabs
              defaultActiveKey="body"
              className="response-tabs"
              style={{ height: '100%' }}
              destroyInactiveTabPane={true} // 销毁不活动的标签页，确保切换时重新渲染
              onChange={(key) => {
                console.log('Tab changed to:', key)
                // 强制重新渲染当前标签页内容
                if (key === 'headers' && responseHeaders) {
                  console.log('Headers tab content:', responseHeaders)
                  // 强制更新状态以触发重新渲染
                  setResponseHeaders({ ...responseHeaders })
                } else if (key === 'tests' && responseStatus) {
                  console.log('Tests tab content:', testResults)
                  // 强制更新状态以触发重新渲染
                  setTestResults([...testResults])
                }
              }}
            >
              <TabPane tab="Body" key="body">
                <div className="response-body-container">
                  {responseBody && (
                    <div className="response-render-controls">
                      <div className="control-group">
                        <span className="control-label">渲染模式:</span>
                        <Select
                          value={responseRenderMode}
                          onChange={(value) => setResponseRenderMode(value)}
                          size="small"
                          className="render-mode-select"
                          popupMatchSelectWidth={false}
                          options={[
                            { value: 'raw', label: '原始内容' },
                            { value: 'preview', label: '预览' },
                          ]}
                        />
                      </div>
                      <div className="control-group">
                        <span className="control-label">语言:</span>
                        <Select
                          value={responseLanguage}
                          onChange={(value) => setResponseLanguage(value)}
                          size="small"
                          className="language-select"
                          popupMatchSelectWidth={false}
                          options={[
                            { value: 'json', label: 'JSON' },
                            { value: 'html', label: 'HTML' },
                            { value: 'xml', label: 'XML' },
                            { value: 'javascript', label: 'JS' },
                            { value: 'css', label: 'CSS' },
                            { value: 'plaintext', label: '纯文本' },
                          ]}
                        />
                      </div>
                    </div>
                  )}

                  {responseRenderMode === 'raw' ? (
                    <div className="monaco-editor-container">
                      <Editor
                        height="100%"
                        defaultLanguage="json"
                        language={responseLanguage}
                        value={responseBody || '// 等待响应...'}
                        theme="light"
                        options={{
                          readOnly: true,
                          minimap: { enabled: true, autohide: true },
                          scrollBeyondLastLine: true,
                          fontSize: 13,
                          wordWrap: 'on',
                          wrappingIndent: 'same',
                          wrappingStrategy: 'advanced',
                          lineNumbers: 'on',
                          lineNumbersMinChars: 3,
                        }}
                      />
                    </div>
                  ) : (
                    <div className="html-preview-container">
                      {responseLanguage === 'html' ? (
                        <iframe
                          srcDoc={responseBody || ''}
                          title="HTML Preview"
                          className="html-preview-frame"
                          sandbox="allow-same-origin"
                        />
                      ) : (
                        <div className="preview-not-available">
                          <Text type="secondary">当前内容类型不支持预览</Text>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </TabPane>
              <TabPane tab="Headers" key="headers">
                {responseHeaders ? (
                  <div
                    className="response-headers"
                    key={`headers-${Date.now()}`}
                  >
                    <Table
                      dataSource={Object.entries(responseHeaders).map(
                        ([key, value], index) => ({
                          key: index,
                          name: key,
                          value: value,
                        }),
                      )}
                      columns={[
                        {
                          title: '名称',
                          dataIndex: 'name',
                          key: 'name',
                          width: '30%',
                          render: (text) => <Text strong>{text}</Text>,
                        },
                        {
                          title: '值',
                          dataIndex: 'value',
                          key: 'value',
                          render: (text) => <Text copyable>{text}</Text>,
                        },
                      ]}
                      size="small"
                      pagination={false}
                      bordered
                      rowKey={(record) => `header-${record.key}`}
                    />
                  </div>
                ) : (
                  <Text type="secondary">暂无响应头信息</Text>
                )}
              </TabPane>
              <TabPane tab="Tests Results" key="tests">
                <div className="test-results" key={`tests-${Date.now()}`}>
                  {responseStatus ? (
                    <>
                      <div className="test-summary">
                        <div className="test-summary-item">
                          <Text strong>总测试数:</Text>
                          <Text>{testResults.length}</Text>
                        </div>
                        <div className="test-summary-item">
                          <Text strong>通过:</Text>
                          <Text style={{ color: '#52c41a' }}>
                            {testResults.filter((t) => t.passed).length}
                          </Text>
                        </div>
                        <div className="test-summary-item">
                          <Text strong>失败:</Text>
                          <Text style={{ color: '#ff4d4f' }}>
                            {testResults.filter((t) => !t.passed).length}
                          </Text>
                        </div>
                      </div>

                      <Table
                        dataSource={testResults.map((test, index) => ({
                          key: index,
                          name: test.name,
                          passed: test.passed,
                        }))}
                        columns={[
                          {
                            title: '测试名称',
                            dataIndex: 'name',
                            key: 'name',
                            width: '70%',
                          },
                          {
                            title: '结果',
                            dataIndex: 'passed',
                            key: 'passed',
                            align: 'center',
                            render: (passed) =>
                              passed ? (
                                <Tag
                                  icon={<CheckCircleOutlined />}
                                  color="success"
                                >
                                  通过
                                </Tag>
                              ) : (
                                <Tag
                                  icon={<CloseCircleOutlined />}
                                  color="error"
                                >
                                  失败
                                </Tag>
                              ),
                          },
                        ]}
                        size="small"
                        pagination={false}
                        bordered
                        rowKey={(_, index) => `test-${index}`}
                      />
                    </>
                  ) : (
                    <Text type="secondary">发送请求后将显示测试结果</Text>
                  )}
                </div>
              </TabPane>
            </Tabs>
          </div>
        </div>
      </div>
    </div>
  )
}

export default HttpPage
